<?php
use think\Db;
use think\Controller;
use taobao\AliSms;


/**
 * 字符串截取，支持中文和其他编码
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
	if (function_exists("mb_substr"))
		$slice = mb_substr($str, $start, $length, $charset);
	elseif (function_exists('iconv_substr')) {
		$slice = iconv_substr($str, $start, $length, $charset);
		if (false === $slice) {
			$slice = '';
		}
	} else {
		$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("", array_slice($match[0], $start, $length));
	}
	return $suffix ? $slice . '...' : $slice;
}

/**
 * 调用系统的API接口方法（静态方法）
 * api('User/getName','id=5'); 调用公共模块的User接口的getName方法
 * api('Admin/User/getName','id=5');  调用Admin模块的User接口
 * @param  string  $name 格式 [模块名]/接口名/方法名
 * @param  array|string  $vars 参数
 */
function api($name,$vars=array()){
    $array     = explode('/',$name);
    $method    = array_pop($array);
    $classname = array_pop($array);
    $module    = $array? array_pop($array) : 'common';
    $callback  = 'app\\'.$module.'\\Api\\'.$classname.'Api::'.$method;
    if(is_string($vars)) {
        parse_str($vars,$vars);
    }
    return call_user_func_array($callback,$vars);
}


/**
 * 获取配置的分组
 * @param string $group 配置分组
 * @return string
 */
function get_config_group($group=0){
    $list = config('config_group_list');
    return $group?$list[$group]:'';
}

/**
 * 获取配置的类型
 * @param string $type 配置类型
 * @return string
 */
function get_config_type($type=0){
    $list = config('config_type_list');  
    return $list[$type];
}


/**
 * 发送短信(参数：签名,模板（数组）,模板ID，手机号)
 */
function sms($signname='',$param=[],$code='',$phone)
{
    $alisms = new AliSms();
    $result = $alisms->sign($signname)->data($param)->code($code)->send($phone);
    return $result['info'];
}


/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}



//时间格式化1
function formatTime($time) {
    $now_time = time();
    $t = $now_time - $time;
    $mon = (int) ($t / (86400 * 30));
    if ($mon >= 1) {
        return '一个月前';
    }
    $day = (int) ($t / 86400);
    if ($day >= 1) {
        return $day . '天前';
    }
    $h = (int) ($t / 3600);
    if ($h >= 1) {
        return $h . '小时前';
    }
    $min = (int) ($t / 60);
    if ($min >= 1) {
        return $min . '分钟前';
    }
    return '刚刚';
}

//时间格式化2
function pincheTime($time) {
     $today  =  strtotime(date('Y-m-d')); //今天零点
      $here   =  (int)(($time - $today)/86400) ; 
      if($here==1){
          return '明天';  
      }
      if($here==2) {
          return '后天';  
      }
      if($here>=3 && $here<7){
          return $here.'天后';  
      }
      if($here>=7 && $here<30){
          return '一周后';  
      }
      if($here>=30 && $here<365){
          return '一个月后';  
      }
      if($here>=365){
          $r = (int)($here/365).'年后'; 
          return   $r;
      }
     return '今天';
}


        function change_status($id,$table,$field)
        {
            $status = Db::name($table)->where('id',$id)->value($field);//判断当前状态情况
            if($status==1)
            {
                $flag = Db::name($table)->where('id',$id)->setField([$field=>0]);
                return json(['code' => 1, 'data' => $flag['data'], 'msg' => '已禁止']);
            }
            else
            {
                $flag = Db::name($table)->where('id',$id)->setField([$field=>1]);
                return json(['code' => 0, 'data' => $flag['data'], 'msg' => '已开启']);
            }

        }

        function change_status1($id,$table,$field,$one,$two)
        {
            $status = Db::name($table)->where('id',$id)->value($field);//判断当前状态情况
            if($status==1)
            {
                $flag = Db::name($table)->where('id',$id)->setField([$field=>0]);
                return json(['code' => 1, 'data' => $flag['data'], 'msg' =>$one]);
            }
            else
            {
                $flag = Db::name($table)->where('id',$id)->setField([$field=>1]);

                if($table=='article'){
                  $article =  Db::name($table)->where('id',$id)->find();
                    if($article['user_id']){
                       $user =  Db::name('member')->where('id',$article['user_id'])->find();

                       // logResult('QQQQQQQQQQ'.$user['open_id'].'|'.$article['title']);
                        if($article['user_id']) {
                            article_shenhe($user['open_id'], $article['title'],$user['instit_id']);
                        }
                    }
                }

                return json(['code' => 0, 'data' => $flag['data'], 'msg' => $two]);
            }

        }


        function deletebyid($id,$table)
        {
            try{
                Db::name($table)->where('id', $id)->delete();
                writelog(session('uid'),session('username'),'用户【'.session('username').'】删除'.$table.'表数据成功(ID='.$id.')',1);
                return ['code' => 1, 'data' => '', 'msg' => '删除数据成功'];
            }catch( PDOException $e){
                return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
            };
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        function logResult($word='')
        {
            $fp = fopen("log.txt", "a");
            flock($fp, LOCK_EX);
            fwrite($fp, "执行日期：" . strftime("%Y%m%d%H%M%S", time()) . "\n" . $word . "\n");
            flock($fp, LOCK_UN);
            fclose($fp);
        }


       function article_shenhe($open_id,$article,$instit_id){


           $wechat = Db::name('wechat')->where('instit_id',$instit_id)->find();

           $options = [
               'token'=> $wechat['token'],
               'encodingaeskey'=> $wechat['encodingaeskey'],
               'appid'=> $wechat['appid'],
               'appsecret'=> $wechat['appsecret']
           ];


           $weObj  = new \com\Wechat($options);

            //	发送快递信息模板消息
            $data['touser']		= $open_id;
            $data['template_id']= 'T1S7Mc6xtJu8HD8OXOjh9sIFku6qilvG1w5nKjeSzWE';
            // $data['url']		= "http://".$_SERVER["HTTP_HOST"]."/index.php?m=default&c=user&a=order_tracking&order_id=".$order_id;
            $data['topcolor']	= '#7B68EE';
            $data['data']['first']['value']	= '您好,您发布的文章已通过审核！';
            $data['data']['first']['color']	= '#743A3A';
            $data['data']['keyword1']['value']	= '《'.$article.'》';
            $data['data']['keyword1']['color']	= '#666666';
            $data['data']['keyword2']['value']	= '审核通过';
            $data['data']['keyword2']['color']	= '#666666';
            $data['data']['remark']['value']	=  date('Y').'年'.date('m').'月'.date('d').'日';
            $data['data']['remark']['color']	= '#3300CC';

            $result =    $weObj->sendTemplateMessage($data);
            return $result;
        }


        function article_shenhe_rejected($open_id,$article,$instit_id,$msg){


            $wechat = Db::name('wechat')->where('instit_id',$instit_id)->find();

            $options = [
                'token'=> $wechat['token'],
                'encodingaeskey'=> $wechat['encodingaeskey'],
                'appid'=> $wechat['appid'],
                'appsecret'=> $wechat['appsecret']
            ];


            $weObj  = new \com\Wechat($options);

            //	发送快递信息模板消息
            $data['touser']		= $open_id;
            $data['template_id']= 'T1S7Mc6xtJu8HD8OXOjh9sIFku6qilvG1w5nKjeSzWE';
            // $data['url']		= "http://".$_SERVER["HTTP_HOST"]."/index.php?m=default&c=user&a=order_tracking&order_id=".$order_id;
            $data['topcolor']	= '#7B68EE';
            $data['data']['first']['value']	= '您好,您发布的文章已被驳回！';
            $data['data']['first']['color']	= '#743A3A';
            $data['data']['keyword1']['value']	= '《'.$article.'》';
            $data['data']['keyword1']['color']	= '#666666';
            $data['data']['keyword2']['value']	= '文章被驳回';
            $data['data']['keyword2']['color']	= '#666666';
            $data['data']['remark']['value']	= '驳回备注:'  .$msg;
            $data['data']['remark']['color']	= '#3300CC';

            $result =    $weObj->sendTemplateMessage($data);
            return $result;
        }


        function send_temp_message($instit_id,$data){

            $wechat = Db::name('wechat')->where('instit_id',$instit_id)->find();

            $options = [
                'token'=> $wechat['token'],
                'encodingaeskey'=> $wechat['encodingaeskey'],
                'appid'=> $wechat['appid'],
                'appsecret'=> $wechat['appsecret']
            ];

            if($wechat){
                $weObj  = new \com\Wechat($options);
                $result =    $weObj->sendTemplateMessage($data);
                return $result;
            }


        }



function convert_arr_key($arr, $key_name)
{
    $arr2 = array();
    foreach($arr as $key => $val){
        $arr2[$val[$key_name]] = $val;
    }
    return $arr2;
}


function get_user_article_count($user_id)
{

     $member = Db::name('member')->field('id,nickname,head_img,group_id,instit_id')->where('id',$user_id)->find();
    // print_R($member);
//    if($member['group_id']==8){
//        $article_count =  Db::name('article')->where("status=1 and (user_id='".$user_id."' or (user_id = 0 and instit_id=".$member['instit_id']."))")->count();
//        $debate_count =  Db::name('debate')->where("user_id='".$user_id."' or (user_id = 0 and instit_id=".$member['instit_id'].")")->count();
//        $essay_count = Db::name('essay')->where('instit_id',$member['instit_id'])->count();
//        $fans_count = Db::name('fans')->where('fans_id',$user_id)->count();
//        $article_count = $article_count+$debate_count+$essay_count;
//    }else{
        $article_count =  Db::name('article')->where("status=1 and user_id  = '".$user_id."'")->count();
        $debate_count =  Db::name('debate')->where("user_id",$user_id)->count();
        $essay =  Db::name('essay')->where("user_id",$user_id)->count();
        $fans_count = Db::name('fans')->where('fans_id',$user_id)->count();
        $article_count = $article_count+$debate_count+$essay;
//    }

    $focus_count = Db::name('fans')->where('user_id',$user_id)->count();
    $result['article_count'] = $article_count;
    $result['fans_count'] = $fans_count;
    $result['focus_count'] = $focus_count;
    $result['id'] = $member['id'];
    $result['nickname'] = $member['nickname'];
    $result['head_img'] = $member['head_img'];
    return $result;

}


function get_article_author($user_id,$instit_id){
        if(empty($user_id)){
            $map = array(
                'instit_id'=>  $instit_id,
                'group_id'=>  8,
            );
            $user =  Db::name('member')->field('nickname,head_img,id')->where($map)->find();
        }else{
            $user =  Db::name('member')->field('nickname,head_img,id')->where('id',$user_id)->find();
        }
    return $user;
}


function user_sign($user_id,$every_sign_integral,$sign_cycle){

    $day = strtotime(date('Y-m-d'));
    $last_sign = Db::name('sign_log')->where(['user_id'=>$user_id,'type'=>'sign'])->order('id desc')->find();
    if($last_sign['sign_time']==$day){
        return -2;
    }

    $member = Db::name('member')->field('integral,integral_num')->where('id',$user_id)->find();

    $cha = $day-$last_sign['sign_time'];
    if($cha==86400){

        $thisintegral = $member['integral_num']*$every_sign_integral;
        $thisintegral_num = $member['integral_num']+1;
        if($thisintegral_num>$sign_cycle){
            $thisintegral_num =1;
        }
    }else{
        $thisintegral = $member['integral_num']*1;
        $thisintegral_num =1;
    }

    $data = array(
        'integral'=>  $thisintegral+$member['integral'],
        'integral_num'=>  $thisintegral_num,
    );

    $result = Db::name('member')->where('id',$user_id)->update($data);

    $datas = array(
        'user_id'=>$user_id,
        'sign_time'=>$day,
        'integral'=>$thisintegral,
        'add_time'=>time(),
        'type'=>'sign'
    );
    Db::name('sign_log')->insert($datas);




    if($result){
        return 1;
    }



}



function add_integral($user_id,$integral,$type){

    $member = Db::name('member')->field('integral,integral_num')->where('id',$user_id)->find();
    $data = array(
        'integral'=>  $integral+$member['integral'],
    );
    $result = Db::name('member')->where('id',$user_id)->update($data);
    $datas = array(
        'user_id'=>$user_id,
        'integral'=>$integral,
        'add_time'=>time(),
        'type'=>$type
    );
    Db::name('sign_log')->insert($datas);

    if($result){
        return 1;
    }

}



function  read_article($article_id){
    $view =  Db::name('article')->field('views')->where('id',$article_id)->find();
    if($view){
        $new = $view['views']+1;
        Db::name('article')->where('id',$article_id)->setField('views',$new);

        $map =array(
            'article_id'=>$article_id,
            'user_id'=>session('user_id'),
            'addtime'=>time()
        );
        Db::name('article_read_log')->insert($map);




    }
}

